################################################################################
##
## Filename:  rtl/Makefile
##
## Project:	  Dramite
##
################################################################################
##
## Copyright (C) 2018, Wenting Zhang
## Copyright (C) 2015-2017, Gisselquist Technology, LLC
##
## This program is free software (firmware): you can redistribute it and/or
## modify it under the terms of  the GNU General Public License as published
## by the Free Software Foundation, either version 3 of the License, or (at
## your option) any later version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY or
## FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
## for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program.  (It's in the $(ROOT)/doc directory.  Run make with no
## target there if the PDF file isn't present.)  If not, see
## <http://www.gnu.org/licenses/> for a copy.
##
## License:	GPL, v3, as defined and found on www.gnu.org,
##		http://www.gnu.org/licenses/gpl.html
##
################################################################################

all:	test design.h
YYMMDD=`date +%Y%m%d`
CXX   := g++
FBDIR := .
VOBJ := obj_dir

.PHONY: test
test: $(VOBJ)/Vbusmaster__ALL.a
SUBMAKE := $(MAKE) --no-print-directory --directory=$(VOBJ) -f
ifeq ($(VERILATOR_ROOT),)
VERILATOR := verilator
else
VERILATOR := $(VERILATOR_ROOT)/bin/verilator
endif
VFLAGS := -Wall -MMD --trace -cc 

SRC := busmaster.v builddate.v					\
	$(CPUSOURCES) $(JTAGBUS) $(PERIPHERALS) $(BIGMATH)

$(VOBJ)/Vbusmaster__ALL.a: $(VOBJ)/Vbusmaster.h $(VOBJ)/Vbusmaster.cpp
$(VOBJ)/Vbusmaster__ALL.a: $(VOBJ)/Vbusmaster.mk
$(VOBJ)/Vbusmaster.h $(VOBJ)/Vbusmaster.cpp $(VOBJ)/Vbusmaster.mk: $(SRC)

$(VOBJ)/V%.cpp $(VOBJ)/V%.h $(VOBJ)/V%.mk: $(FBDIR)/%.v
	$(VERILATOR) $(VFLAGS) $*.v

$(VOBJ)/V%.cpp: $(VOBJ)/V%.h
$(VOBJ)/V%.mk:  $(VOBJ)/V%.h
$(VOBJ)/V%.h: $(FBDIR)/%.v

design.h: busmaster.v
	@echo "Building design.h"
	@echo "// " > $@
	@echo "// Do not edit this file, it is automatically generated!" >> $@
	@echo "// To generate this file, \"make design.h\" in the rtl directory." >> $@
	@echo "// " >> $@
	@echo "#ifndef DESIGN_H" >> $@
	@echo "#define DESIGN_H" >> $@
	@echo >> $@
	@grep "^\`" $< | grep -v default_nettype | grep -v include | sed -e '{ s/^`/#/ }' | sed -e ' s/busmaster.v/design.h/' >> $@
	@echo >> $@
	@echo "#endif // DESIGN_H" >> $@

builddate.v: 
	@echo "\`define DATESTAMP $(YYMMDD)" > $@

$(VOBJ)/V%__ALL.a: $(VOBJ)/V%.mk
	$(SUBMAKE) V$*.mk

.PHONY: clean
clean:
	rm -rf $(VOBJ)/*.mk
	rm -rf $(VOBJ)/*.cpp
	rm -rf $(VOBJ)/*.h
	rm -rf $(VOBJ)/

#
# Note Verilator's dependency created information, and include it here if we
# can
DEPS := $(wildcard $(VOBJ)/*.d)

ifneq ($(DEPS),)
include $(DEPS)
endif
